<template>
  <el-dialog :visible.sync="dialog" :title="isAdd ? '新增用户' : '编辑用户'" append-to-body width="570px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"/>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-radio v-for="item in dicts" :key="item.id" v-model="form.enabled" :label="item.value">{{ item.label }}</el-radio>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model.number="form.phone" :disabled="!isAdd"/>
      </el-form-item>
      <el-form-item label="等级" prop="enabled">
        <el-radio v-for="item in gradeList" :key="item.key" v-model="form.member_type" :label="item.key">{{ item.value }}</el-radio>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="部门">
        <treeselect v-model="deptId" :options="depts" :style="style" placeholder="选择部门" @select="selectFun" />
      </el-form-item>
      <el-form-item label="岗位">
        <el-select v-model="jobId" :style="style" placeholder="请先选择部门">
          <el-option
            v-for="(item, index) in jobs"
            :key="item.name + index"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px;" label="角色">
        <el-select v-model="roleIds" style="width: 450px;" multiple placeholder="请选择">
          <el-option
            v-for="(item, index) in roles"
            :disabled="level !== 1 && item.level <= level"
            :key="item.name + index"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { hex_md5 } from '@/utils/md5'
import { add, edit, addLoginUser, updateLoginUser, getUserByPhone, updateAppUserMemberType } from '@/api/user'
import { getDepts } from '@/api/dept'
import { getAll, getLevel } from '@/api/role'
import { getAllJob } from '@/api/job'
import Treeselect from '@riophae/vue-treeselect'
import Cookies from 'js-cookie'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: { Treeselect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    dicts: {
      type: Array,
      required: true
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!this.isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      dialog: false, loading: false,
      form: {
        member_type: 4,
        old_member_type: 4,
        user_id: 0,
        username: '',
        email: '',
        enabled: 'true',
        roles: [],
        job: { id: '' },
        dept: { id: '' },
        phone: null,
        companyId: ''
      },
      roleIds: [], roles: [], depts: [], deptId: null, jobId: null, jobs: [], style: 'width: 184px', level: 3,
      gradeList: [
        { key: 3, value: '省长' },
        { key: 2, value: '团长' }
      ],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        enabled: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    const explorer = navigator.userAgent
    if (explorer.indexOf('Chrome') >= 0) {
      this.style = 'width: 184px'
    } else {
      this.style = 'width: 172px'
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.form.dept.id = this.deptId
      this.form.job.id = this.jobId
      this.form.companyId = Cookies.get('company_id')
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.deptId === null || this.deptId === undefined) {
            this.$message({
              message: '部门不能为空',
              type: 'warning'
            })
          } else if (this.jobId === null) {
            this.$message({
              message: '岗位不能为空',
              type: 'warning'
            })
          } else if (this.roleIds.length === 0) {
            this.$message({
              message: '角色不能为空',
              type: 'warning'
            })
          } else {
            this.loading = true
            this.form.roles = []
            const _this = this
            this.roleIds.forEach(function(data, index) {
              const role = { id: data }
              _this.form.roles.push(role)
            })
            if (this.isAdd) {
              this.doAdd()
            } else {
              if (this.form.old_member_type > this.form.member_type) {
                this.$message({
                  message: '角色不能进行降级操作',
                  type: 'warning'
                })
                this.loading = false
                return
              }
              this.doEdit()
            }
          }
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        if (res.username) {
          // 新增用户到单点登录的后台中
          const phone = this.form.phone + ''
          const password = '123456'
          const companyid = this.form.companyId
          const timestamp = Math.round(new Date()) + ''
          const signcode = hex_md5(phone + password + companyid + timestamp)
          const data = { phone: phone, password: password, companyid: companyid, timestamp: timestamp, signcode: signcode }
          addLoginUser(data).then(res => {
            if (res.code === '100000140001') {
              // 手机号已注册（在单点登陆系统中存在），则修改用户信息
              updateLoginUser(data)
              return
            }
          })
          // 新增App用户
          if (this.form.member_type === 3 || this.form.member_type === 2) {
            // 单独的接口，更新用户等级
            const info = { user_id: this.form.user_id, member_type: this.form.member_type, phone: this.form.phone, user_name: this.form.username }
            updateAppUserMemberType(info)
          }
          this.resetForm()
          this.$notify({
            title: '添加成功',
            message: '默认密码：123456',
            type: 'success',
            duration: 2500
          })
        }
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        // 修改用户信息时，当用户是当前登录的用户信息，需要更新登录人的用户信息
        if (this.form.phone === this.user.phone) {
          getUserByPhone(this.form.phone).then(res => {
            if (res.content) {
              const user = res.content[0]
              user.dept = user.dept.name ? user.dept.name : ''
              user.job = user.job.name ? user.job.name : ''
              this.$store.commit('SET_USER', user)
            }
          })
        }
        // 修改App用户
        if (this.form.member_type === 3 || this.form.member_type === 2) {
          // 单独的接口，更新用户等级
          const info = { user_id: this.form.user_id, member_type: this.form.member_type, phone: this.form.phone, user_name: this.form.username }
          updateAppUserMemberType(info)
        }
        this.resetForm()
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.deptId = null
      this.jobId = null
      this.roleIds = []
      this.form = { username: '', email: '', enabled: 'false', roles: [], job: { id: '' }, dept: { id: '' }, phone: null, companyId: '' }
    },
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    getJobs(id) {
      const enabled = this.isAdd ? true : null
      getAllJob(id, enabled).then(res => {
        this.jobs = res.content
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    getDepts() {
      const enabled = this.isAdd ? true : null
      getDepts({ enabled: enabled }).then(res => {
        this.depts = res.content
      })
    },
    isvalidPhone(str) {
      const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
      return reg.test(str)
    },
    selectFun(node, instanceId) {
      this.getJobs(node.id)
    },
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(err => {
        console.log(err.response.data.message)
      })
    }
  }
}
</script>

<style scoped>

</style>
